package com.handong.handserialprogram.thread;

import android.content.Context;
import android.util.Log;

import com.handong.handserialprogram.R;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.model.status.FootRingStatus;
import com.handong.handserialprogram.model.status.RingResponse;
import com.handong.handserialprogram.module.qrscan.update.FootUpdateActivity;
import com.handong.handserialprogram.module.serialport.SerialPortUtil;
import com.handong.handserialprogram.threadpool.FindRing;
import com.handong.handserialprogram.utils.CheckUtil;
import com.handong.handserialprogram.utils.EventBusUtil;
import com.handong.handserialprogram.utils.FootRingNewUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.SPUtil;
import com.handong.handserialprogram.voice.VoiceImpl;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;

import cn.pda.serialport.Tools;

/**
 * Created by zhongqiu on 2019/9/26.
 */

public class ReadNewRunnable extends BaseRunnable {
    private static final byte DATA_LENGTH = 15;
    //    private static final byte DATA_LENGTH = 23;
    private static final byte TIME_WAIT = 12;
    private InputStream mReadStream;
    private CopyOnWriteArrayList<FootRingNewEntity> mRingList;
    public boolean IsFresh = true;
    //private byte mIdHigh, mIdLow;
    private VoiceImpl mVoiceImpl;
    private Context mAppContext;
    private SerialPortUtil mSerialPortUtil;

    private boolean mIsPlayWarningVoice = false;//是否开启警报
    private boolean mIsUploadLocation = false;
    private byte mWarningCount, mUploadCount;
    public boolean isFirst = true;
    private byte mTestCount = 0;
    public boolean isPause = false;
    public boolean isStopRecycle = false;
    public String ringId = "";
    private boolean isPlaying = false;


    public boolean isWorking = false;
    private FootUpdateActivity footUpdateActivity;

//    private CallBackUtil.OnSendDataListener onSendDataListener;

//    /**
//     * 注册回调接口的方法，供外部调用
//     * @param onSendDataListener
//     */
//    public void setOnSendDataListener(CallBackUtil.OnSendDataListener onSendDataListener) {
//        this.onSendDataListener = onSendDataListener;
//    }

    public ReadNewRunnable(SerialPortUtil serialPortUtil, InputStream readStream, CopyOnWriteArrayList<FootRingNewEntity> ringList,
                           Context context, boolean isPlayWarningVoice) {
        this.mReadStream = readStream;
        this.mRingList = ringList;
        this.mSerialPortUtil = serialPortUtil;
        this.mAppContext = context;
        this.mIsPlayWarningVoice = isPlayWarningVoice;
    }

    public void setEntityList(CopyOnWriteArrayList<FootRingNewEntity> list) {
//        ListIterator<FootRingNewEntity> iterator =mRingList.listIterator();
//        iterator.set(list);
        mRingList = list;
    }


    public boolean DoWork(String ringId, boolean isTimeOut) {
        if (mRingList == null) {
            return false;
        }
       /* if (SerialPortUtil.TEST_DEBUG) {
            //测试情况
            if (mRingList != null && !mRingList.isEmpty()) {
                EventBusUtil.post(mRingList);
                FootRingNewEntity entity = mRingList.get;
                playWarningRing(entity);

                if (entity.getActionOrder() == RingResponse.LOGOUT_ORDER) {
                    if (mTestCount == 5) {
                        entity.setNormalWork(false);
                        entity.setActionOrder(RingResponse.NO_ACTION_ORDER);
                        //EventBusUtil.post(new RingResponse("88CE", RingResponse.LOGOUT_ORDER, true));
                        mTestCount = 0;
                    }
                    mTestCount++;
                }
            }
        } else {*/
        try {
            //查找更新有效的脚环
            //boolean result=false;

            return search4ActiveFootRing(isTimeOut);


        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        // }

    }

    @Override
    public void work() throws RuntimeException {
        if (!isStopRecycle) {
            DoWork("", false);
            refreshAllFootRing();//刷新全部脚环


            if (isPlaying) {
                if (mWarningCount >= 9) {
                    mWarningCount = 0;
                    isPlaying = false;
                } else {
                    mWarningCount++;
                }
            } else {
                isPlaying = playWarningRing();
                mWarningCount = 0;
            }

        }


//        if (mIsWorking && mIsUploadLocation) {//如果已绑定脚环刷新距离
//
//            if (mUploadCount == 0) {//只上传一次到服务器
//                if (!mRingList.isEmpty()&&!isPause) {
//                    mSerialPortUtil.refreshRingList();//上传到服务器
////                    if (isFirst){
////                        mSerialPortUtil.startMission(SPUtil.getStringValue(SPUtil.MISSION_ID));
////                        isFirst=false;
////                    }
//                }
//                mUploadCount++;
//            } else {
//                mUploadCount++;
//                if (mUploadCount == TIME_WAIT) {
//                    mUploadCount = 0;
//                }
//            }
//        }

    }

//    private void CheckIsEscrpt()
//    {
//        for (FootRingNewEntity entity:mRingList) {
//            entity.calculateTime();//计算时间
//        }
//    }

    /**
     * 查找并激活脚环。
     */
    private FindRing findRing = new FindRing();
    int sentTime = 0;
    int number = 1;

    private boolean search4ActiveFootRing(boolean isTimeOut) throws IOException {
        boolean isReadCompelate = false;

        //long firstTime=System.currentTimeMillis();
        //JLog.d(TAG, "fist: "+ String.valueOf(System.currentTimeMillis()-firstTime));
        if (mReadStream.available() > 0) {
            byte[] buff = new byte[mReadStream.available()];//获取全部数据
            mReadStream.read(buff);
            if (buff[0] == 0x68 && buff.length>25) {
                number++;
                if (number == 5) {
                    number = 1;
                }
                Log.d("脚环数据", "正常通信:" + Tools.byteToHexString(buff).substring(0, 30) + "-===============" + String.valueOf(number));
                isReadCompelate = dealActiveBufferByte(buff);//添加或处理脚环命令
            }

            if (buff[0] == 0x75 && buff[1] == 0x77 && buff[2] == 0x01) {
                sentTime++;
                if (buff[4] == 0x52 || buff[4] == 0x46) {
                    findRing.setRingTag();
                }
                Log.d("脚环数据", "ID请求" + Tools.byteToHexString(buff) + "次数:" + sentTime);

            }
            if (buff[0] == 0x06 && buff[1] == 0x43) {
                Log.d("脚环数据", "YMODEM 升级:" + Tools.byteToHexString(buff));
            } else {
                Log.d("脚环数据", "数据:" + Tools.byteToHexString(buff));
            }
        }
        return isReadCompelate;
    }

    /**
     * 添加或处理脚环命令
     */
    private Vector<FootRingNewEntity> refFootRings = new Vector<>();

    private boolean dealActiveBufferByte(byte[] buff) {
        boolean isReadTrue = false;
        if (mRingList == null) {
            return isReadTrue;
        }

        FootRingNewEntity entity = null;
        int index = 0;
        int len = buff.length;
        refFootRings.clear();
        do {

            if (buff[index] != 104 || buff[index + 1] != 100) {//hd 不是脚环发送命令
                index++;//循环到hd为止
                continue;//结束本次循环
            }
            if (index + DATA_LENGTH > len) {//数据是否完整。
                break;
            }
            byte[] tempBuff = new byte[DATA_LENGTH];//DATA_LENGTH个字节表示一个脚环
            System.arraycopy(buff, index, tempBuff, 0, DATA_LENGTH - 1);

            if (CheckUtil.u8CheckSum8Calibration(tempBuff) != buff[(index + DATA_LENGTH - 1)]) {
                JLog.d(TAG, "正常通信 Error Data:" + Tools.byteToHexString(tempBuff));
                index++;//循环到hd为止
                continue;
            }
            if (!Tools.byteLinkByteToHexString(buff, index + 3, 2).equals(SPUtil.getStringValue(SPUtil.IMEI_CRC)) && !Tools.byteLinkByteToHexString(buff, index + 3, 2).equals("0000")) {
                JLog.d(TAG, "正常通信 Other Android Data:" + Tools.byteToHexString(tempBuff));
                index++;
                continue;
            }
            entity = FootRingNewUtil.getFootRingFromList(tempBuff, mRingList);
            if (entity != null && (ringId.equals(entity.getRingID()) || ringId.equals(""))) {
                isReadTrue = true;
            }
            Log.d("脚环数据", "正常通信:" + Tools.byteToHexString(tempBuff)+"线程名："+Thread.currentThread().getName());
            refreshFootRingNewEntity(tempBuff, entity);//添加脚环-设置脚环
            refFootRings.add(entity);
            index += DATA_LENGTH;
        } while (len - index >= DATA_LENGTH);//未读取完数据继续读取数据。
        return isReadTrue;
        //refreshAllFootRing(refFootRings);//刷新全部脚环
    }
    //int testpower=100;

    /**
     * 发送处理脚环结果
     */
    private void sendDealOrder(FootRingNewEntity entity, byte order, boolean isSuccess) {
        if (entity == null) {
            return;
        }
        entity.resetActionCount();
        entity.setActionOrder(RingResponse.NO_ACTION_ORDER);//重置为已处理
        EventBusUtil.post(new RingResponse(entity.getRingID(), order, isSuccess));
    }

    private void sendDealOrder(byte order, boolean isSuccess) {
        EventBusUtil.post(new RingResponse(order, isSuccess));
    }

    private long ReceiveTime = 0;

    /**
     * 解析数据实体
     */
    private void refreshFootRingNewEntity(byte[] buff, FootRingNewEntity entity) {
//        if (mRingList == null) {
//            return;
//        }
//        if (!ringId.equals("") && !Tools.byteLinkByteToHexString(buff, 5, 2).equals(ringId)) {
//            return;
//        }
        Log.d("脚环数据", "正常通信: ID" + Tools.byteLinkByteToHexString(buff, 5, 2));
//        Log.d("Active Data", "rinfID:" + ringId + " :" + Tools.byteLinkByteToHexString(buff, 5, 2));
        JLog.d(TAG, "Active Data:" + Tools.byteToHexString(buff));
        if (entity == null) {
            //没有该脚环添加
            entity = new FootRingNewEntity();
            entity.setCreateTime(System.currentTimeMillis() / 1000);
            mRingList.add(entity);
        }

//        if (!ringId.equals("")) {
//            entity.setCurrentIndex(buff[2]);
//            JLog.d(TAG, "序号"+buff[2]);
//        }
        //软件版本
        int version = buff[2];
        String versionHigh = String.valueOf((version >> 5) & 0x07);
        String versionLow = String.valueOf(version & 0x1F);
        entity.setVersion("V4." + versionHigh + "." + versionLow);
        Log.d("获取数据", "V" + versionHigh + "." + versionLow);
//        if (!ringId.equals("")&&entity.getCurrentIndex()==buff[2])
//        {
//            JLog.d(TAG, "序号重复");
//            return;
//        }
//        if (!ringId.equals("")) {
//            entity.setCurrentIndex(buff[2]);
//            JLog.d(TAG, "序号"+buff[2]);
//        }


        ReceiveTime++;
        if (ReceiveTime >= 100000L) {
            ReceiveTime = 0;
        }
        JLog.d("获取数据", "接收次数: " + ReceiveTime);

        //设置手持机id，若为0则没绑定
        String imei_crc = Tools.byteLinkByteToHexString(buff, 3, 2);

        entity.setIMEI_CCR(imei_crc);

        Log.d("获取数据", "手持机ID:" + imei_crc);
        //设置脚环序号

        String id = Tools.byteLinkByteToHexString(buff, 5, 2);
        entity.setRingID(id);
        entity.setReceiveData(true);
        Log.d("获取数据", "脚环id " + id);

        int funCode = buff[7];
        String funCodeStr = String.valueOf(funCode);
        int data_len = buff[8];
        String data_lenStr = String.valueOf(data_len);
        JLog.d("获取数据", "功能码: " + funCodeStr + "data_len:" + data_len);


        int index = 9;//从第9位开始取数据。
        //脚环距离
        byte tempDistance = buff[index++];//取第9位
        byte tempDistanceFloat = buff[index++];
        int distance = Tools.twoByteToInt(tempDistance, tempDistanceFloat);


        if (!ringId.equals("") && entity.getStatus() == FootRingStatus.ESCAPE && entity.getEscapeFirst()) {
            entity.setEscapeFirst(false);
            return;
        }
        if ((tempDistance == 0xC3 && tempDistanceFloat == 0x50) || (!ringId.equals("") && tempDistance == 0x00 && tempDistanceFloat == 0x00)) {
            JLog.d("获取数据", "这儿有问题1");
            return;
        }

        float distanceFloat = CheckUtil.floatRoundToInt(distance);
        Log.d("获取数据", "距离:" + distanceFloat);
        if (distanceFloat < 0.00F && isStopRecycle) {
            JLog.d("获取数据", "这儿有问题2");
            return;
        }

        int receiveCount = entity.getReceiveCount() + 1;
        entity.setReceiveCount(receiveCount);
        float totalDistanceFloat = entity.getTotalRingDistance() + distanceFloat;
        entity.setTotalRingDistance(totalDistanceFloat);
        float averageDistanceFloat = (float) (Math.round(totalDistanceFloat / receiveCount * 10)) / 10;//求平均值并保留一位小数

        Log.d(TAG, "当前小数脚环距离: " + distanceFloat + ",总数：" + totalDistanceFloat + ",次数:" + receiveCount + ",平均数：" + averageDistanceFloat);
        if (entity.getReceiveCount() != 0) {
            entity.setActualRingDistance(averageDistanceFloat);
        } else {
            entity.setActualRingDistance(0.0F);
        }

        if (!entity.isResponseDistance()) {
            entity.setResponseDistance(true);
        }


        byte checkStatus = buff[index++];
        entity.setCheckStatus(checkStatus);
        //锁状态
        int lockType = (checkStatus >> 7) & 0x01;
        if (mIsPlayWarningVoice && !entity.isWithdraw() && !entity.isEmpower() && entity.getLockType() != FootRingNewEntity.LOCK_OPEN && lockType == FootRingNewEntity.LOCK_OPEN) {//开锁报警
            if (mVoiceImpl == null) mVoiceImpl = VoiceImpl.getInstance(mAppContext);
            mVoiceImpl.addSound(R.raw.warning_lock_open);
        }
        if (lockType == FootRingNewEntity.LOCK_OPEN) {
            if (entity.isEmpower()) {
                entity.setLockType(FootRingNewEntity.LOCK_EMPOWER_OPEN);
            } else {
                entity.setLockType(FootRingNewEntity.LOCK_OPEN);
            }

        } else {

            entity.setLockType(FootRingNewEntity.LOCK_CLOSE);
        }
        //防拆状态
        int broken = (checkStatus >> 6) & 0x01;
        if (FootRingNewEntity.LOCK_OPEN == broken) {//拆报警
            if (mIsPlayWarningVoice && entity.getBrokenType() != 1 && !entity.isEmpower()) {
                if (mVoiceImpl == null) mVoiceImpl = VoiceImpl.getInstance(mAppContext);
                mVoiceImpl.addSound(R.raw.warning_ring_broken);
            }
            entity.setBrokenType(1);
        } else {
            entity.setBrokenType(0);
        }
        //超距状态
        boolean isOverHang = ((checkStatus >> 5) & 0x01) == 0x01;
        entity.setOverHang(isOverHang);
        //越界
        boolean isOverLeval = ((checkStatus >> 4) & 0x01) == 0x01;
        entity.setOverLeval(isOverLeval);

        //脱逃状态
        boolean isEscape = ((checkStatus >> 3) & 0x01) == 0x01;
        entity.setEscape(isEscape);
        //是否震动
        boolean isShake = ((checkStatus >> 2) & 0x01) == 0x01;
        entity.setShake(isShake);
        //是否低电量
        boolean isPowerLow = ((checkStatus >> 1) & 0x01) == 0x01;
        entity.setPowerLow(isPowerLow);
        //是否低电量关机
        boolean isPowerDown = ((checkStatus >> 0) & 0x01) == 0x01;
        entity.setPowerDown(isPowerDown);

        JLog.d("获取状态数据", "锁状态: " + lockType + "防拆:" + broken + "超距：" + isOverHang + "越界：" + isOverLeval + "震动：" + isShake + "低电量：" + isPowerLow + "关机：" + isPowerDown);
        if (isPowerDown) {
            FootRingNewUtil.unbind(entity);
            entity.setNormalWork(false);
            sendDealOrder(entity, RingResponse.LOGOUT_ORDER, true);
            JLog.d("获取数据", "关机注销");
            return;
        }

        //检测状态

        byte modelStatus = buff[index++];
        //是否注销
        boolean isLoginOut = (modelStatus >> 7 & 0x01) == 0x01;
        if (isLoginOut && !isStopRecycle) {

            FootRingNewUtil.unbind(entity);
            entity.setNormalWork(false);
            sendDealOrder(entity, RingResponse.LOGOUT_ORDER, true);
            if (!isWorking) {
                mRingList.remove(entity);
                mSerialPortUtil.setRingList(mRingList);
            }

            //mRingList.remove(entity);

            return;
        }
        entity.setLoginOut(isLoginOut);
        //是否返回状态
        boolean isResult = (modelStatus >> 6 & 0x01) == 0x01;
        entity.setResult(isResult);
        //是否正在报警
        boolean isSouding = (modelStatus >> 5 & 0x01) == 0x01;
        entity.setSouding(isSouding);
        boolean isAudioError = (modelStatus >> 4 & 0x01) == 0x01;
        entity.setAudioError(isAudioError);
        //UWB是否初始化成功
        boolean isUwebError = (modelStatus >> 3 & 0x01) == 0x01;
        entity.setUwbError(isUwebError);
        //4G模块初始化成功
        boolean is4gError = (modelStatus >> 2 & 0x01) == 0x01;
        entity.setIs4gError(is4gError);
        //Sim是否正常
        boolean isSimError = (modelStatus >> 1 & 0x01) == 0x01;
        entity.setSimError(isSimError);
        //发送imei错误提示
        if (isSimError && !entity.isSimError()) {
            EventBusUtil.post(new RingResponse(id, RingResponse.SIM_ERROR, false));
        }
        //WiFi模块是否正常
        boolean isWifiError = (modelStatus & 0x01) == 0x01;
        entity.setWifiError(isWifiError);

        JLog.d("获取数据", "注销: " + isLoginOut + "结果:" + isResult + "报警：" + isSouding + "音频：" + isAudioError + "uwb：" + isUwebError + "4G：" + is4gError + "SIM：" + isSimError + "WIFI:" + isWifiError);
        //电量
        int power = (int) (buff[index++] & 0xff);
        entity.setTruePower(power);
        if (power >= 40) {
            entity.setRingPower((int) (power * 1.433 + 32.18));
        } else {
            entity.setRingPower((int) (power * 1.207 + 41.43));
        }

        JLog.d("获取数据", "电量：" + power);

        //设置状态
        if (imei_crc.equals("0000") || FootRingNewEntity.LOCK_OPEN == broken) {
            entity.setNormalWork(false);
        } else {
            entity.setNormalWork(true);
        }
//        FootRingNewUtil.setMyBingding(entity, imei_crc);
        if (entity.isHandAlarm()) {
            entity.setHandAlarm(false);
        }

        if (!mSerialPortUtil.currentCode.equals("") && mSerialPortUtil.currentCode.equals(entity.getRingID())) {
            mSerialPortUtil.mBindedRingList.remove(entity.getRingID());
            mSerialPortUtil.sendIMEI();
        }
        //设置当前的超距位
        if (!entity.isOverSetDistance() && entity.getActualRingDistance() >= entity.getSetRingDistance()) {
            entity.setOverSetDistance(true);
        }
        if (entity.isOverSetDistance() && entity.getActualRingDistance() < entity.getSetRingDistance()) {
            entity.setOverSetDistance(false);
        }

        mSerialPortUtil.setRingList(mRingList);

        //处理命令
        if (entity != null && entity.getActionOrder() != RingResponse.NO_ACTION_ORDER) {
            switch (entity.getActionOrder()) {
                case RingResponse.ACTIVATE_ORDER://脚环激活
                    if (imei_crc.equals(SPUtil.getStringValue(SPUtil.IMEI_CRC))) {
                        FootRingNewUtil.unbind(entity);
                        sendDealOrder(entity, RingResponse.INIT_2GNET_SUCCESS, true);
                        //mSerialPortUtil.order++;
                    }
                    break;
                case RingResponse.UPDATE_DISTANCE_ORDER://设置距离
                    sendDealOrder(entity, RingResponse.UPDATE_DISTANCE_ORDER, true);
                    break;

                case RingResponse.CLOSE_ALARM_RESPONSE://关闭警报
                    if (RingResponse.CLOSE_ALARM_RESPONSE == entity.getActionOrder()) {
                        sendDealOrder(entity, RingResponse.CLOSE_ALARM_RESPONSE, true);
                        mSerialPortUtil.closeAlarmOrder2Server(entity.getRingID());
                    } else {
                        entity.setActionOrder(RingResponse.NO_ACTION_ORDER);
                        mSerialPortUtil.resetOrder2Server(entity.getRingID());
                    }
                    mUploadCount = 5;
                    break;

            }
        }

        entity.resetTime();//重置时间
        //发送命令
        //onSendDataListener.onSend(entity);
    }


    /**
     * 刷新脚环-有命时令执行-处理超时
     *
     * @param entity 更新的脚环
     */
    private void refreshFootRing(FootRingNewEntity entity) {
        if (mRingList == null) {//|| (mRingList.isEmpty())
            JLog.d(TAG, "4");
            return;
        }
        if (null == entity) {
            JLog.d(TAG, "5");
            return;
        }
        //处理有命令时未处理完成-超时处理
        if (RingResponse.NO_ACTION_ORDER != entity.getActionOrder()) {
            switch (entity.getActionOrder()) {
                case RingResponse.ACTIVATE_ORDER://脚环激活
                    activateNoResponse(entity, RingResponse.ACTIVATE_ORDER);
                    break;

                case RingResponse.INIT_2GNET_SUCCESS://自检状态-自己设置的
                    dealRingSelfCheck(entity, RingResponse.INIT_2GNET_SUCCESS);
                    break;

                case RingResponse.LOGOUT_ORDER://脚环休眠
                    dealExceptActivateOrder(entity, RingResponse.LOGOUT_ORDER);
                    break;

                case RingResponse.CLOSE_ALARM_RESPONSE://报警关闭
                    dealOverTimeOrder(entity, RingResponse.CLOSE_ALARM_RESPONSE);
                    break;

                case RingResponse.UPDATE_DISTANCE_ORDER://设置距离更新
                    dealOverTimeOrder(entity, RingResponse.UPDATE_DISTANCE_ORDER);
                    break;

                case RingResponse.CLOSE_ALARM_FROM_SERVER://从服务器报警关闭
                    entity.addActionCount();
                    if (entity.getActionCount() == 3) {
                        entity.setAction(false);
                        entity.setActionOrder(RingResponse.NO_ACTION_ORDER);
                    }
                    break;
                case RingResponse.PARAMETER_SET://参数设置模式应答
                    dealOverTimeOrder(entity, RingResponse.PARAMETER_SET);
                    break;
                case RingResponse.PARAMERT_LOGOUT://退出参数设置模式
                    dealOverTimeOrder(entity, RingResponse.PARAMERT_LOGOUT);
                    break;
                case RingResponse.SEVER_IP_SET://服务器参数设置应答
                    dealOverTimeOrder(entity, RingResponse.SEVER_IP_SET);
                    break;
                case RingResponse.ALARM_SOUND_SET://报警声设置应答
                    dealOverTimeOrder(entity, RingResponse.ALARM_SOUND_SET);
                    break;
            }
            JLog.d(TAG, "ActionOrder:" + entity.getActionCount());
        }
        //entity.setReceiveData(false);

//        if (isRefresh) {
//
//        }
//        else {
        //特殊处理，前三包会测距失败，所以前三包不计算逃脱
        if (entity.getDataCount() >= 3) {
            entity.calculateTime();//计算时间
        } else {
            entity.setDataCount(entity.getDataCount() + 1);
        }

//        }
//        if (entity.getStatus()==FootRingStatus.ESCAPE) {
//
//        }
        addWarningRing(entity);//警报
    }

    /**
     * 更新全部脚环
     */
    public void refreshAllFootRing() {
        if (mRingList == null) {//|| (mRingList.isEmpty())
            JLog.d(TAG, "6");
            return;
        }
        //CopyOnWriteArrayList<FootRingNewEntity> arrayList=mRingList.
        for (FootRingNewEntity entity : mRingList) {
            if (!entity.isReceiveData() && entity.getStatus() == FootRingStatus.ESCAPE) {
                entity.setEscapeFirst(true);
            }
            if (!isStopRecycle && ((System.currentTimeMillis() / 1000 - entity.getCreateTime()) >= 155)) {
                //若当前为查找状态，增加定时删除entity
                FootRingNewUtil.unbind(entity);
                entity.setNormalWork(false);
                sendDealOrder(entity, RingResponse.LOGOUT_ORDER, true);
                if (!isWorking) {
                    try {
                        mRingList.remove(entity);
                        mSerialPortUtil.setRingList(mRingList);
                    } catch (Exception e) {
                        Log.d(TAG, "refreshAllFootRing: ", e);
                    }
                    //mRingList.remove();
                }


                //mRingList.remove(entity);

            }
            refreshFootRing(entity);

            if (IsFresh) {
                entity.setReceiveCount(0);
                entity.setTotalRingDistance(0.0F);
                //entity.setActualRingDistance(0.0F);
            }
        }


//            if(refFootRings!=null&&refFootRings.contains(entity)){
//                refreshFootRing(entity);//刷新脚环
//            }else{
//                refreshFootRing(entity);//刷新脚环
//            }


        if (IsFresh || ringId.equals("")) {
            Log.d(TAG, "更新界面");
            EventBusUtil.post(mRingList);//返回列表
            IsFresh = false;

        }


    }


    /**
     * 激活应答-超时处理（10秒）
     */
    private void activateNoResponse(FootRingNewEntity entity, byte order) {
        if (entity.getStatus() == FootRingStatus.ESCAPE) {
            entity.calculateTime();
            sendDealOrder(entity, order, false);
            return;
        }
        entity.addActionCount();
        JLog.d(TAG, "Activate activateNoResponse" + entity.getActionCount());
        if (entity.getActionCount() == 4) {
            mSerialPortUtil.activateFootRing(entity.getRingID());
            return;
        }
        if (entity.getActionCount() == 7) {
            sendDealOrder(entity, order, false);
        }
    }

    /**
     * 自检-超时处理(超过20秒)
     */
    private void dealRingSelfCheck(FootRingNewEntity entity, byte order) {
        entity.addActionCount();
        JLog.d(TAG, "Activate Receive Response:" + entity.getActionCount());

        if (entity.getActionCount() == FootRingNewEntity.LONG_WAIT) {
            sendDealOrder(entity, order, false);
        }
    }

    /**
     * 处理休眠超时
     */
    private void dealExceptActivateOrder(FootRingNewEntity entity, byte order) {
        if (entity.getStatus() == FootRingStatus.ESCAPE) {
            sendDealOrder(entity, order, false);
            return;
        }

        entity.addActionCount();
//        if (entity.getActionCount() == 4) {
//            if (order == RingResponse.LOGOUT_ORDER) {
//                mSerialPortUtil.logoutFootRing(entity.getRingID());
//            }
//           /* if (order != RingResponse.LOGOUT_ORDER) {
//                sendDealOrder(entity, order, false);
//                return;
//            } else {
//                mSerialPortUtil.logoutFootRing(entity.getRingID());
//            }*/
//        }
        //超过三次没收到数据了 注销成功

        if (entity.getStopMissionNoDataCount() >= 2) {
            FootRingNewUtil.unbind(entity);
            entity.setNormalWork(false);
//            if(!isWorking)
//            {
//                mRingList.remove(entity);
//                mSerialPortUtil.setRingList(mRingList);
//            }
//            sendDealOrder(entity, order, true);
            return;
        } else {
            if (entity.isReceiveData() && entity.isLoginOutAlarm()) {
                entity.setStopMissionNoDataCount(0);
                entity.setStopMissionReceive(true);
            } else {
                if (entity.isStopMissionReceive()) {
                    entity.setStopMissionNoDataCount(entity.getStopMissionNoDataCount() + 1);
                }

            }

        }
//        if (entity.isSendLoginOut())
//        {
//            entity.setLoginOutAlarm(true);
//        }
//        if (entity.getActionCount() == 7) {
//            if (order == RingResponse.LOGOUT_ORDER) {
//                sendDealOrder(entity, order, false);
//            }
//        }


    }

    /**
     * 处理部分命令-超时处理
     * 超过10秒超时处理
     */
    private void dealOverTimeOrder(FootRingNewEntity entity, byte order) {
        if (entity.getStatus() == FootRingStatus.ESCAPE) {
            sendDealOrder(entity, order, false);
            return;
        }
        entity.addActionCount();
        if (entity.getActionCount() == 7) {
            sendDealOrder(entity, order, false);
        }
    }

    /**
     * 添加Sound
     *
     * @param res
     */
    public void addSound(int res) {
        if (!mIsPlayWarningVoice) {
            mWarningCount = 0;
            return;
        }
        if (mVoiceImpl == null) {
            mVoiceImpl = VoiceImpl.getInstance(mAppContext);
        }
        mVoiceImpl.addSound(res);
    }

    /**
     * 添加警报
     */
    private void addWarningRing(FootRingNewEntity entity) {
//        if (!entity.isNormalWork()) {
//            return;
//        }
        if (!mIsPlayWarningVoice) {
            return;
        }
        if (mVoiceImpl == null) {
            mVoiceImpl = VoiceImpl.getInstance(mAppContext);
        }
        int powerlow = entity.getPowerlowCount();
        if (FootRingStatus.ESCAPE != entity.getStatus() && entity.getTruePower() >= 0 && entity.getTruePower() < 40) {
            if (powerlow >= 20) {
                mVoiceImpl.addSound(R.raw.warning_ring_low_power);//低电量
                entity.setPowerlowCount(0);
            } else {
                powerlow += 1;
                entity.setPowerlowCount(powerlow);
            }

        }

        if ((isWorking && FootRingStatus.ESCAPE != entity.getStatus() && entity.getSetRingDistance() <= entity.getActualRingDistance())) {
            mVoiceImpl.addSound(R.raw.warning_exception);//异常音效
        }
        if (isWorking && entity.getStatus() == FootRingStatus.ESCAPE) {
            mVoiceImpl.addSound(R.raw.warning_escape);//逃脱音效
        }
    }

    /**
     * 添加警报
     */
    private boolean playWarningRing() {
        if (!mIsPlayWarningVoice) {
            return false;
        }
        if (mVoiceImpl == null) {
            mVoiceImpl = VoiceImpl.getInstance(mAppContext);
        }
        // TODO: 2017/11/23 可以考虑重置标识符，来缩短首次报警的时间差。
//        if (mWarningCount != 0) {
//            mWarningCount++;
//            if(!isStopRecycle)
//            {
//                if (mWarningCount >= 15) {
//                    mWarningCount = 0;
//                }
//            }
//            else{
//                if (mWarningCount >= 5) {
//                    mWarningCount = 0;
//                }
//            }
//
//            return;
//        }
//        mWarningCount++;

        return mVoiceImpl.playVoice();
    }

    public void setPlayWarningVoice(boolean playWarningVoice) {
        mIsPlayWarningVoice = playWarningVoice;
    }

    public void setUploadLocation(boolean uploadLocation) {
        mIsUploadLocation = uploadLocation;
    }


    @Override
    public void releaseRes() {
        mRingList = null;
        mSerialPortUtil = null;
        mReadStream = null;
        mAppContext = null;
        if (mVoiceImpl != null) {
            mVoiceImpl.releaseRes();
            mVoiceImpl = null;
        }
        mWarningCount = 0;
        mUploadCount = 0;
        //mIdHigh = 0;
        // mIdLow = 0;
    }
}
